import os
import xpinyin
import pyperclip
import random
import time

def start():
    filepath='./resource_utf8.txt'
    go=xpinyin.Pinyin()
    dict_string={}
    with open(filepath,'r',encoding='utf-8') as fp:
        for item in fp.readlines():
            string=item.split(',')[1].replace('"','')
            if len(string)==4:
                head=go.get_pinyin(string,u"-").split("-")[0]
                if dict_string.get(head)!=None:
                    list=dict_string[head]
                    list.append(string)
                    dict_string.update({head:list})
                else:
                    dict_string.update({head:[]})
        # 结果保存在dict_string
    return dict_string

def paste_find(string):
    try:
        go = xpinyin.Pinyin()
        head = go.get_pinyin(string, u"-").split('-')[3]
        return head
    except:
        print("格式转换出错")
        return False

if __name__=="__main__":
    print("猜成语程序启动 复制成语即可 自动粘贴到粘贴板")
    dict_string=start()
    old_message=pyperclip.paste()
    while True:
        message = pyperclip.paste()
        if message != old_message:
            print(message)
            if len(message) == 4:
                last=paste_find(message)
                if last!=False:
                    length=len(dict_string[last])
                    rd=random.randint(0,length-1)
                    string=dict_string[last][rd]
                    pyperclip.copy(string)
                    old_message=string
                    print("[ %s ]已经粘贴到粘贴板"%string)
                    continue
        old_message = message

